<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '卡密列表' : '卡密列表' }}</span>
      </template>
      <el-card shadow="never">
        <!-- 搜索表单 -->
        <!-- <role-search @search="reload" /> -->
        <!-- 数据表格 -->

        <ele-pro-table ref="table"
                       :columns="columns"
                       :datasource="datasource"
                       tool-class="ele-toolbar-form"
                       row-key="id">
          <!-- 表头工具栏 -->
          <template v-slot:toolbar>
            <el-button size="small"
                       type="primary"
                       icon="el-icon-plus"
                       class="ele-btn-icon"
                       @click="onExport(list)">
              导出
            </el-button>

          </template>

          <template v-slot:img="{ row }">
            <div><img class="categoryImages"
                   :src="row.img"
                   alt="" /></div>
          </template>
          <template v-slot:content="{ row }">
            <div v-html="row.content"></div>
          </template>
          <template v-slot:round_str="{ row }">
            <div>
              {{ row.round_str }}
              <el-link type="primary"
                       :underline="false"
                       @click="copyAddress(row.round_str)">
                复制
              </el-link>
            </div>
          </template>
          <template v-slot:status="{ row }">
            {{authorityFn(row.status)}}
          </template>
          <!-- 状态列 -->

          <template v-slot:level="{ row }">
            <div>
              {{ row.level==0?'普通用户':'vip用户' }}
            </div>
          </template>
          <template v-slot:sort="{ row }">
            <i class="sort-handle el-icon-rank ele-text-secondary"
               style="cursor: move"></i>
            <div v-if="false">{{ row }}</div>
          </template>
          <!-- 操作列 -->
          <template v-slot:action="{ row }">

            <el-popconfirm class="ele-action"
                           title="确定要删除该条信息？"
                           @confirm="remove(row)">
              <template v-slot:reference>
                <el-link type="danger"
                         :underline="false"
                         icon="el-icon-delete">
                  删除
                </el-link>
              </template>
            </el-popconfirm>
          </template>
        </ele-pro-table>
      </el-card>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';

// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { utils, writeFile } from 'xlsx';
import { upload } from '@/api/saveImg/index'
import { camiList, deleteCami } from '@/api/vIPLevel/index'
export default {
  name: 'pictureEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {

    return {
      storageMode: 2,
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      columns: [

        // {
        //   prop: 'id',
        //   label: '排序',
        //   sortable: 'custom',
        //   showOverflowTooltip: true,
        //   minWidth: 30,
        //   align: 'center',
        //   slot: 'sort'
        // },
        {
          columnKey: 'index',
          type: 'index',
          label: '序号',
          width: 60,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },

        {
          prop: 'name',
          label: '等级名字',
          sortable: 'custom',
          width: 105,
          align: 'center',
          showOverflowTooltip: true,


        },
        {
          prop: 'level',
          label: '分类名称',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          slot: 'level'
        },
        {
          prop: 'status',
          label: '卡密当前状态',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          slot: 'status'
        },
        {
          prop: 'desc',
          label: '描述',
          sortable: 'custom',

          showOverflowTooltip: true,

          align: 'center'
        },
        {
          prop: 'round_str',
          label: '卡密',
          sortable: 'custom',

          showOverflowTooltip: true,

          align: 'center',
          slot: 'round_str'
        },
        {
          prop: 'create_time',
          label: '创建时间',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: true,
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue, 'yyyy-MM-dd HH:mm');
          }
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 105,
          align: 'center',
          resizable: false,
          slot: 'action',
          hideInSetting: true,
          showOverflowTooltip: true
        }
      ],
      dialogImageUrl: '',
      fileList: [],
      list: [],
      dialogVisible: false,
      // 表单验证规则

      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false,
      id: null
    };
  },
  activated () {

  },
  computed: {

    authorityFn: function () {
      return function (status) {

        let orderStatus = '';
        // status订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款)
        orderStatus =
          status == 0 ? '全部' : status == 1 ? '未使用' : status == 2 ? ' 已经使用' : ' ';

        return orderStatus;
      };
    },


  },
  methods: {

    // 复制链接
    copyAddress (val) {
      var copyInput = document.createElement("input"); // 创建元素
      //val是要复制的内容
      copyInput.setAttribute("value", val);
      document.body.appendChild(copyInput);
      copyInput.select();
      try {
        var copyed = document.execCommand("copy");
        if (copyed) {
          document.body.removeChild(copyInput);

          this.$message.success("复制成功");
        }
      } catch {
        this.$message.error("复制失败，请检查浏览器兼容");
      }
    },
    onExport (row) {
      row.then(res => {
        console.log(res.list)

        const array = [
          ['序号', '等级名称', '卡密状态', '卡密', '创建时间']
        ];
        res.list.forEach((d, i) => {
          array.push([i + 1, d.name, d.status == 1 ? '未使用' : '已经使用', d.round_str, d.create_time]);
        });
        const sheet = utils.aoa_to_sheet(array);
        // 如果需要设置列宽可以这样写
        sheet["!cols"] = [
          { wch: 10 },
          { wch: 50 },
          { wch: 20 },
          { wch: 20 },

        ];
        writeFile(
          {
            SheetNames: ['Sheet1'],
            Sheets: {
              Sheet1: sheet
            }
          },
          '卡密数据.xlsx'
        );
      })

    },

    /* 表格数据源 */
    async datasource ({ page, limit, where }) {
      this.list = camiList({
        page,
        limit,
        ...where,


      });

      return this.list
    },
    /* 刷新表格 */
    reload (where) {
      this.$refs.table.reload({ page: 1, where: where });
    },
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.img = this.imageUrl;
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    /* 删除61 */
    remove (row) {
      const loading = this.$loading({ lock: true });
      deleteCami({
        id: row.id,


      })
        .then((msg) => {
          loading.close();
          this.$message.success(msg);
          this.reload({ level_id: this.id });
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file) {

      this.aliFn(file)
    },
    // 阿里云
    async aliFn (file) {
      this.loading = true;

      let files = file.raw;

      console.log(files)
      // 构建请求参数
      let params = new FormData();
      console.log(params);

      //   params.append('signature', '132321313');
      params.append('file', files);
      console.log(params);

      //   let config = {
      //     headers: {
      //       'Access-Control-Allow-Origin': '*',
      //       'x-oss-callback-Authorization': getToken()
      //     }
      //   };

      const res = await upload(params);
      //   let result = await axios.post(res.host, param, config);
      //   let url = res.host + '/' + date + suffix;
      console.log(res);
      if (res.code == 0) {
        this.form.img = res.data.url
        this.loading = false;
      }
      //   this.form.categoryImages = url;
      //   this.imageUrl = url;
      //   this.loading = false;
    },


  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.id = this.data.id;
            this.reload({ level_id: this.id })

            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });


        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
